package leetcode.leetcode83;

/**
 * @author czt
 * @version 1.0
 * @since 2024/12/18
 *
 * 删除有序链表中重复节点，保留一个
 */
public class Leetcode83 {

    public ListNode deleteDuplicates1(ListNode head) {
        // 当没有节点或者没有下一个节点时，直接返回head
        if (head == null || head.next == null) {
            return head;
        }

        // 节点数 >=2
        ListNode p1 = head;
        ListNode p2;
        while((p2 = p1.next) != null) {
            if (p2.val == p1.val) {
                // 删除p2
                p1.next = p2.next;
            } else {
                // 向后平移
                p1 = p1.next;
            }
        }
        return head;
    }

    public ListNode deleteDuplicates2(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        if (head.val == head.next.val) {
            return deleteDuplicates2(head.next);
        } else {
            head.next = deleteDuplicates2(head.next);
            return head;
        }
    }
}
